<?php

namespace Ignus\View\TokenParser;

use Ignus\View\Node\Expression\Constant;
use Ignus\View\TokenParser;
use Ignus\View\Error\Syntax;
use Ignus\View\Token;
use Ignus\View\Node;

class UseParser extends TokenParser
{
    public function parse(Token $token)
    {
        $template = $this->parser->getExpressionParser()->parseExpression();
        if (!$template instanceof Constant) {
            throw new Syntax('The template references in a "use" statement must be a string.', $token->getLine());
        }

        $stream = $this->parser->getStream();

        $targets = array();
        if ($stream->test('with')) {
            $stream->next();

            do {
                $name = $stream->expect(Token::NAME_TYPE)->getValue();

                $alias = $name;
                if ($stream->test('as')) {
                    $stream->next();

                    $alias = $stream->expect(Token::NAME_TYPE)->getValue();
                }

                $targets[$name] = new Constant($alias, -1);

                if (!$stream->test(Token::PUNCTUATION_TYPE, ',')) {
                    break;
                }

                $stream->next();
            } while (true);
        }

        $stream->expect(Token::BLOCK_END_TYPE);

        $this->parser->addTrait(new Node(array('template' => $template, 'targets' => new Node($targets))));

        return null;
    }

    public function getTag()
    {
        return 'use';
    }
}
